//
//  MerchandiseListController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/20.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "MerchandiseListController.h"
#import "MerchandiseEditController.h"
#import "MerchandiseCell.h"
#import "JFBLoadingAnimation.h"
#import "BatchOptController.h"

#import "ApiUpdateProdStatus.h"

#define screen_Width [UIScreen mainScreen].bounds.size.width
#define screen_Height [UIScreen mainScreen].bounds.size.height

@interface MerchandiseListController()<JFBDataSourceRefreshDelegate,UIGestureRecognizerDelegate>
{
    NSInteger currentPage;
    NSInteger itemPerPage;
    NSInteger total;
    NSInteger up;
    NSInteger down;
    
}
@property (weak, nonatomic) IBOutlet UIBarButtonItem *batchOptionItem;
@property (nonatomic,strong) NSDictionary *dataDic;
@property (nonatomic,assign) NSInteger    currentIndex;

@end

@implementation MerchandiseListController


- (NSDictionary*) dataDic{
    if (!_dataDic) {
        _dataDic = @{
                     @0 : [NSMutableArray array],
                     @1 : [NSMutableArray array],
                     @2 : [NSMutableArray array]
                     };
    }
    return _dataDic;
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.items = [@[] mutableCopy];
   
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
    currentPage = 1;
    itemPerPage = 10;
    
    self.currentItems = [@[] mutableCopy];
    
    [self setupUI];
    
    
    
    
    // 当是非移动商户时 “批量操作” 隐藏
    NSInteger category1_id = [[[NSUserDefaults standardUserDefaults] objectForKey: @"category1_id"] intValue];
    
    if (category1_id != 25) {
        self.batchOptionItem.enabled = false;
        self.batchOptionItem.title = @"";
    }
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
    
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(refreshTable)];
      [self.tableView.footer setTitle: @"已经没有更多的数据了" forState: MJRefreshFooterStateNoMoreData];
    
}


- (void) setupUI {
    //改变button的frame值跟下面label的frame值
    self.allRed.frame = CGRectMake(0, 41, screen_Width/3, 3);
    self.upRed.frame = CGRectMake(screen_Width/3, 41, screen_Width/3, 3);
    self.downRed.frame = CGRectMake((screen_Width/3)*2, 41, screen_Width/3, 3);
    //设置button的frame
    self.allShelfButtonClick.frame = CGRectMake(0, 0, screen_Width/3, 44);
    self.upShelfButtonClick.frame = CGRectMake(screen_Width/3, 0, screen_Width/3, 44);
    self.downShelfButtonClick.frame = CGRectMake((screen_Width/3)*2, 0, screen_Width/3, 44);
    //给三个button添加点击事件
    [self.allShelfButtonClick addTarget:self action:@selector(allShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
    [self.upShelfButtonClick addTarget:self action:@selector(upShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
    [self.downShelfButtonClick addTarget:self action:@selector(downShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
    //进来先隐藏已上架跟未上架的横条
    self.upRed.hidden = YES;
    self.downRed.hidden = YES;
    self.upShelfNumber.textColor = [UIColor grayColor];
    self.upShelfLabel.textColor = [UIColor grayColor];
    self.downShelfNumber.textColor = [UIColor grayColor];
    self.downShelfLabel.textColor = [UIColor grayColor];
    
    [self allShelfButtonClickTo];
    
//    self.navigationItem.title = [NSString stringWithFormat:@"%@（%lu）", self.merchandiseCategory.categoryName, (unsigned long)self.merchandiseCategory.total];
    self.navigationItem.title = [NSString stringWithFormat:@"%@", self.merchandiseCategory.categoryName];
    [self.upShelfCheck setImage:[UIImage imageNamed:@"check2"] forState:UIControlStateNormal];
    [self.upShelfCheck setImage:[UIImage imageNamed:@"check2_on"] forState:UIControlStateSelected];
    [self.downShelfCheck setImage:[UIImage imageNamed:@"check2"] forState:UIControlStateNormal];
    [self.downShelfCheck setImage:[UIImage imageNamed:@"check2_on"] forState:UIControlStateSelected];
    
    UITapGestureRecognizer *upGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onUpLabelClick:)];
    self.upShelfLabel.userInteractionEnabled=YES;
    upGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    upGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.upShelfLabel addGestureRecognizer:upGesture];
    
    if( self.merchandiseCategory ) {
        [self reload:nil];
    }
    
    
    UITapGestureRecognizer *downGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onDownLabelClick:)];
    self.downShelfLabel.userInteractionEnabled=YES;
    downGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    downGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.downShelfLabel addGestureRecognizer:downGesture];
    
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
}
-(void)reload {
    [self reload:@"hello"];
}
- (void)reload:(__unused id)sender {
    
    
    //   JFBLoadingAnimation * animation = [[JFBLoadingAnimation alloc] init:self.tableView];
    //    [JFBMerchandiseDS loadMerchandiseList:^(NSArray *merchandiseList, NSError *error) {
    //        self.items = [@[] mutableCopy];
    //       for( JFBMerchandiseDS *ds in merchandiseList ) {
    //           [self.items addObject:ds];
    //       }
    ////       [self tableViewDataSourceFilte];
    //       [self refreshCount];
    //       [animation stop];
    //       [self commonDataDic];
    //
    //   } categoryId:self.merchandiseCategory.categoryId ut:[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"] pager:nil];
    
    //
    [self.dataDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSMutableArray * _Nonnull obj, BOOL * _Nonnull stop) {
        [obj removeAllObjects];
    }];
     NSInteger tempCurrentPage = currentPage;
    if(currentPage>1){
       
        itemPerPage = currentPage*itemPerPage;
        currentPage = 1;

    }
    
    [self loadDataForWeb];
    currentPage =tempCurrentPage;
    itemPerPage = 10;

    
    //    [self commonDataDic];
}
-(void)tableViewDataSourceFilte{
    [self.currentItems removeAllObjects];
    for( JFBMerchandiseDS *ds in self.items ) {
        if( self.currentFilter == -1 ||  (ds.mpStatus && self.currentFilter == 4) || (!ds.mpStatus && self.currentFilter == 5)  ) {
            [self.currentItems addObject:ds];
        }
    }
    [self.tableView reloadData];
}
- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) loadDataForWeb {
    
    JFBLoadingAnimation * animation = [[JFBLoadingAnimation alloc] init:self.tableView];
    NSDictionary *parameter = @{@"categoryId":[NSNumber numberWithInteger:self.merchandiseCategory.categoryId],
                                @"currentPage":[NSNumber numberWithInteger:currentPage],
                                @"itemsPerPage":[NSNumber numberWithInteger:itemPerPage],
                                @"ut":[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]};
    [[JFBAPIClient sharedClient:true] GET:@"/back-product/getMerchantProductList.do" parameters:parameter success:^(NSURLSessionDataTask *task, id JSON) {
        [animation stop];
        [self.items removeAllObjects];
        if([JSON[@"code"] integerValue] == 0) {
            
            NSDictionary *data = [JSON valueForKey:@"data"];
            total = [[data valueForKeyPath:@"total"] integerValue];
            up = [[data valueForKeyPath:@"shelvesNum"] integerValue];
            down = [[data valueForKeyPath:@"pullOffShelvesNum"] integerValue];
            
            NSArray *response  = [data valueForKeyPath:@"merchantProductList"];
            NSArray *array =[NSArray yy_modelArrayWithClass:[JFBMerchandiseDS class] json:response];
            [self.items addObjectsFromArray:array];
            
                [self commonDataDic];
            
        }else if ([JSON[@"code"] integerValue] == 99){
            UIViewController* viewController;
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [animation stop];
    }];
}


- (void) refreshTable{
    currentPage++;
    [self loadDataForWeb];
    //    [self commonDataDic];
    
    [self.tableView.footer endRefreshing];
    
}
- (void) commonDataDic{
    //    [self.dataDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSMutableArray * _Nonnull obj, BOOL * _Nonnull stop) {
    //        [obj removeAllObjects];
    //    }];
    
    [(NSMutableArray*)self.dataDic[@0] addObjectsFromArray:self.items];
    for( JFBMerchandiseDS *ds in self.items) {
        if( ds.mpStatus == 4) {
            [(NSMutableArray*)self.dataDic[@1] addObject:ds];
        }else{
            [(NSMutableArray*)self.dataDic[@2] addObject:ds];
        }
    }
    [self refreshCount];
    [self.tableView reloadData];
    
}
//- (void) updateAfterChangeProductStatus{
//    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
//    [JFBMerchandiseDS switchUpAndDownShelf:^(BOOL isSuccess, NSError *error) {
//        [SVProgressHUD dismiss];
//        if( isSuccess ) {
//            //            _merchandise.mpStatus = !_merchandise.mpStatus;
//            //            self.shangJiaLabel.text = _merchandise.mpStatus ? @"已上架" : @"已下架";
//            //            [self.swShelfBtn setSelected:_merchandise.mpStatus];
//            [JFBUIAnimation alertTips:@"修改成功"];
//            [self.delegate reload];
//        }
//    } merchandiseID:_merchandise.mpId oldStatus:_merchandise.mpStatus newStatus: self.shelfSwitch.on? 4 : 5 saleType:_merchandise.saleType];
//}
// =============更新数量=======
-(void)refreshCount{
//    NSMutableArray *temp = @{}.mutableCopy;
    
    
//    NSString *allNum  = [NSString stringWithFormat:@"%ld",[self.dataDic[@0] count]];
//    NSString *upNum   = [NSString stringWithFormat:@"%ld",[self.dataDic[@1] count]];
//    NSString *downNum = [NSString stringWithFormat:@"%ld",[self.dataDic[@2] count]];
//    if (allNum.length) {
//        self.allShelfNumber.text = [NSString stringWithFormat:@"%@",allNum];
//    }else{
//        self.allShelfNumber.text = @"0";
//    }
//    if (upNum.length) {
//        self.upShelfNumber.text = [NSString stringWithFormat:@"%@",upNum];
//    }else{
//        self.upShelfNumber.text = @"0";
//    }
//    if (downNum.length) {
//        self.downShelfNumber.text = [NSString stringWithFormat:@"%@",downNum];
//    }else{
//        self.downShelfNumber.text = @"0";
//    }
    
    self.allShelfNumber.text = [NSString stringWithFormat:@"%ld",total];
    self.upShelfNumber.text = [NSString stringWithFormat:@"%ld",up];
    self.downShelfNumber.text = [NSString stringWithFormat:@"%ld",down];
    
}


-(void)onUpLabelClick:(UITapGestureRecognizer *)sender{
    [self upBtnClick:nil];
}

-(void)onDownLabelClick:(UITapGestureRecognizer *)sender{
    [self downBtnClick:nil];
}

//商品的上下架
- (void)clickCellUpDownBtnWithCell:(MerchandiseCell*)cell Mode:(JFBMerchandiseDS *)mode
{
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    [JFBMerchandiseDS switchUpAndDownShelf:^(BOOL isSuccess, NSError *error) {
        [SVProgressHUD dismiss];
        if( isSuccess ) {
            [JFBUIAnimation alertTips:@"修改成功"];
            [self reload];
        }
    } merchandiseID:mode.mpId oldStatus:mode.mpStatus newStatus: mode.mpStatus==4? 5 :4 saleType:mode.saleType];
    
}


#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [(NSMutableArray*)self.dataDic[@(self.currentIndex)] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    JFBMerchandiseDS * ds = [(NSMutableArray*)self.dataDic[@(self.currentIndex)] objectAtIndex:indexPath.row];
     MerchandiseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"merchandiseCellIdentifier" forIndexPath:indexPath];
    UISwitch *shelfSwitch = [cell viewWithTag:10086];
    if(ds.saleType==3){
        shelfSwitch.hidden = YES;
    }
   
    
    cell.merchandise = ds;
    [cell setClickUpDown:^(MerchandiseCell *cell,JFBMerchandiseDS *mode) {
        [self clickCellUpDownBtnWithCell:cell Mode:mode];
        
        shelfSwitch.selected = !shelfSwitch.selected;
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _currentMerchandise = [self.dataDic[@(self.currentIndex)] objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"merchandiseEditIdentifier" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if( [segue.identifier isEqualToString:@"merchandiseEditIdentifier"] ) {
        MerchandiseEditController * controller = (MerchandiseEditController*)segue.destinationViewController;
        controller.merchandise = _currentMerchandise;
        controller.delegate = self;
    } else if( [segue.identifier isEqualToString:@"batchOptIdentifier"] ) {
        BatchOptController * controller = (BatchOptController*)segue.destinationViewController;
        controller.items = self.items;
        controller.merchandiseCategory = self.merchandiseCategory;
        controller.delegate = self;
    }
}

-(void)viewDidLayoutSubviews {
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
#pragma mark -三个按钮的点击事件实现
/*
 [self.allShelfButtonClick addTarget:self action:@selector(allShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
 [self.upShelfButtonClick addTarget:self action:@selector(upShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
 [self.downShelfButtonClick addTarget:self action:@selector(downShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
 
 */

#pragma mark -点击全部
-(void)allShelfButtonClickTo{
    if (self.currentFilter == 4 && self.currentFilter == 5) {//全部
        [self.allShelfButtonClick setSelected:true];
        self.currentFilter = 6;
    }else if (self.currentFilter == 4){//上架
        [self.upShelfButtonClick setSelected:false];
        [self.downShelfButtonClick setSelected:false];
        self.currentFilter = 6;
    }else{//下架
        [self.allShelfButtonClick setSelected:true];
        [self.downShelfButtonClick setSelected:false];
        [self.upShelfButtonClick setSelected:false];
        self.currentFilter = 6;
    }
    self.allShelflabel.textColor = [UIColor redColor];
    self.allShelfNumber.textColor = [UIColor redColor];
    self.allRed.hidden = NO;
    self.upShelfNumber.textColor = [UIColor grayColor];
    self.upShelfLabel.textColor = [UIColor grayColor];
    self.upRed.hidden = YES;
    self.downShelfNumber.textColor = [UIColor grayColor];
    self.downShelfLabel.textColor = [UIColor grayColor];
    self.downRed.hidden = YES;
    
    self.currentIndex = 0;
    //    [self commonDataDic];
    [self.tableView reloadData];
}
#pragma mark -点击已上架
-(void)upShelfButtonClickTo{
    if (self.currentFilter == 6) {//全部
        [self.upShelfButtonClick setSelected:true];
        self.currentFilter = 4;
    }else if (self.currentFilter == 4){//上架
        [self.upShelfButtonClick setSelected:false];
        self.currentFilter = 4;
    }else{//下架
        [self.upShelfButtonClick setSelected:true];
        [self.downShelfButtonClick setSelected:false];
        self.currentFilter = 4;
    }
    
    self.currentIndex = 1;
    [self.tableView reloadData];
    
    //    [self commonDataDic];
    
    self.allShelflabel.textColor = [UIColor grayColor];
    self.allShelfNumber.textColor = [UIColor grayColor];
    self.allRed.hidden = YES;
    self.upShelfNumber.textColor = [UIColor redColor];
    self.upShelfLabel.textColor = [UIColor redColor];
    self.upRed.hidden = NO;
    self.downShelfNumber.textColor = [UIColor grayColor];
    self.downShelfLabel.textColor = [UIColor grayColor];
    self.downRed.hidden = YES;
}
#pragma mark -点击未上架
-(void)downShelfButtonClickTo{
    if( self.currentFilter == 6 ) {
        [self.downShelfButtonClick setSelected:true];
        self.currentFilter = 5;
    }else if( self.currentFilter == 4 ) {
        [self.upShelfButtonClick setSelected:false];
        [self.downShelfButtonClick setSelected:true];
        self.currentFilter = 5;
    }else {
        [self.downShelfButtonClick setSelected:false];
        self.currentFilter = 5;
    }
    self.currentIndex = 2;
    [self.tableView reloadData];
    //    [self commonDataDic];
    self.allShelflabel.textColor = [UIColor grayColor];
    self.allShelfNumber.textColor = [UIColor grayColor];
    self.allRed.hidden = YES;
    self.upShelfNumber.textColor = [UIColor grayColor];
    self.upShelfLabel.textColor = [UIColor grayColor];
    self.upRed.hidden = YES;
    self.downShelfNumber.textColor = [UIColor redColor];
    self.downShelfLabel.textColor = [UIColor redColor];
    self.downRed.hidden = NO;
}








@end
